使用NotificationListenerService需要用户手动授权,该服务主要是获取系统通知的相关信息,这里只分析应用为什么不会被杀,使用通知内容这里不做分析。
NotificationListenerService的使用需要三步:
1.写一个类继承NotificationListenerService:
public class NotificationService extends NotificationListenerService {
@Override
public void onListenerConnected() {
System.out.println("zyf onListenerConnected");
super.onListenerConnected();
}
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
System.out.println("zyf onNotificationPosted");
super.onNotificationPosted(sbn);
}
}
2.在AndroidManifest.xml中注册该服务并声明相关权限:
<service
android:name="com.example.notification.NotificationService"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE" >
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
3.开启监听通知的功能:
这一步需要用户手动授权,在“Settings” > “Security” > “Notification access”中,引导用户勾选自己的应用程序。此时服务连接成功、收到通知时就会有相应的log打出了。设置界面并不好找,所以可以在代码中帮助用户跳转到设置界面,如果服务没有被授权则跳转到设置界面:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String string = Settings.Secure.getString(getContentResolver(),
"enabled_notification_listeners");
System.out.println("zyf 已经允许使用通知权的应用:" + string);
// 数据库中保存的格式:包名/服务名:包名/服务名,如:
// com.example.notification/com.example.notification.NotificationService
// :com.example.smartface/com.example.smartface.notification.SmartFaceListenerService
if (!string.contains(NotificationService.class.getName())) {
startActivity(new Intent(
"android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"));
}
}
}
到这里,只要用户授权,你的应用程序就不会被杀了。很简单吧,下面分析为什么不会被杀:
先看下NotificationListenerService服务的启动,总共就三种启动该服务的途径,分别是接收到PACKAGE相关的广播(安装、更新、卸载等)触发启动、多用户之间的切换触发启动、数据库变化触发启动。
接收到PACKAGE相关的广播触发启动:
开机时,会进行NotificationManagerService服务的初始化操作:
public NotificationManagerService(Context context) {
super(context);
}
@Override
public void onStart() {
. . .
// 初始化NotificationListeners,它是ManagedServices的子类
mListeners = new NotificationListeners();
. . .
// 注册接收PACKAGE相关的广播
IntentFilter pkgFilter = new IntentFilter();
pkgFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
pkgFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
pkgFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
pkgFilter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
pkgFilter.addDataScheme("package");
getContext().registerReceiverAsUser(mPackageIntentReceiver, UserHandle.ALL, pkgFilter, null,
null);
. . .
// 发布服务到系统
publishBinderService(Context.NOTIFICATION_SERVICE, mService);
. . .
}
// 接收PACKAGE相关的广播
private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getA